package com.webchat.chat.service.impl;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.webchat.chat.core.dto.customerDto.UserDto;
import com.webchat.chat.core.redis.RedisService;
import com.webchat.chat.core.tools.RedisConstant;
import com.webchat.chat.core.tools.ShiroUtil;
import com.webchat.chat.dao.SocketClientMapper;
import com.webchat.chat.model.SocketClient;
import com.webchat.chat.service.SocketClientService;
import com.webchat.chat.core.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;


/**
 * Created by admin on 2018-06-29.
 */
@Service
@Transactional
public class SocketClientServiceImpl extends AbstractService<SocketClient> implements SocketClientService {
    @Resource
    private SocketClientMapper socketClientMapper;

    @Resource
    private RedisService redisService;

    @Resource
    private SocketIOServer socketIOServer;

    @Override
    public SocketClient findSocketClientByClientId(String clientId) {
        return socketClientMapper.selectSocketClientByClientId(clientId);
    }

    @Override
    public SocketClient findSocketClientByUserId(String userId) {
        return socketClientMapper.selectSocketClientByUserId(userId);
    }

    @Override
    public List<SocketClient> findByRoomId(String roomId) {
        return socketClientMapper.selectByRoomId(roomId);
    }

    @Override
    public SocketIOClient getSocketIOClientByUserId(String userId) {
        SocketClient client =  socketClientMapper.selectSocketClientByUserId(userId);
        Long mostSignificantBits = client.getMostSignificantBits();
        Long leastSignificantBits = client.getLeastSignificantBits();
        UUID uuid = new UUID(mostSignificantBits, leastSignificantBits);
        return socketIOServer.getClient(uuid);
    }

    @Override
    public List<UserDto> findCustomer(String tenantCode) {
        List<UserDto> users = socketClientMapper.findCustomer(tenantCode);
        return users;
    }

    @Override
    public void changeCustomerAuditStatus(String[] userIds, Boolean flag) {
        for (String userId : userIds) {
            SocketClient socketClient = socketClientMapper.selectSocketClientByUserId(userId);
            socketClient.setAduit(flag);
            socketClientMapper.updateByPrimaryKey(socketClient);
            SocketClient client = (SocketClient) redisService.getMapField(RedisConstant.SCOKET_CLIENT_C + ShiroUtil.getTenantCode(), userId);
            client.setAduit(flag);
            redisService.addMap(RedisConstant.SCOKET_CLIENT_CS + ShiroUtil.getTenantCode(), userId, client);
        }
    }
}
